package com.vf.s.mvc.biz.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.jfinal.aop.Inject;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import com.vf.core.controller.BaseController;
import com.vf.core.model.ZtreeNode;
import com.vf.core.util.PinYinUtil;
import com.vf.core.util.UuidUtil;
import com.vf.s.common.model.biz.BizLayer;
import com.vf.s.common.model.biz.Point;
import com.vf.s.common.plugins.shiro.ShiroKit;
import com.vf.s.common.plugins.shiro.SimpleUser;
import com.vf.s.common.vector.kml.KmlLine;
import com.vf.s.common.vector.kml.KmlParser;
import com.vf.s.common.vector.kml.KmlPolygon;
import com.vf.s.common.vector.kml.KmlProperty;
import com.vf.s.mvc.biz.service.BizLayerService;

public class BizLayerController extends BaseController {

	@Inject
	private BizLayerService srv;

	public void index() {
		render("list.html");
		
//		try {
//			List<BizLayer> bizLayers=BizLayer.dao.find("SELECT * FROM "+BizLayer.TABLE_NAME);
//			for(BizLayer bizLayer:bizLayers) {
//				bizLayer.setCode(PinYinUtil.getPinyin(bizLayer.getName()));
//				bizLayer.update();
//			}
//			
//			List<BizPolygon> bizPolygons=BizPolygon.dao.find("SELECT * FROM "+BizPolygon.TABLE_NAME);
//			for(BizPolygon bizPolygon:bizPolygons) {
//				bizPolygon.setCode(PinYinUtil.getPinyin(bizPolygon.getName()));
//				BizLayer bizLayer=BizLayer.dao.findFirst("SELECT * FROM "+BizLayer.TABLE_NAME+" WHERE CODE=? ",bizPolygon.getCode());
//				if(bizLayer!=null) {
//					bizPolygon.setLayerId(bizLayer.getId());
//				}
//				bizPolygon.update();
//			}
//			
//		}catch (Exception e) {
//			// TODO: handle exception
//		}
		
		
	} 
	
//	public void listData() {
//		List<BizLayer> list = BizLayer.dao.find(
//				"SELECT T.*, (CASE  WHEN (SELECT COUNT(ID) AS COUNT FROM "+BizLayer.TABLE_NAME+" WHERE PARENTID=T.ID)>0 THEN TRUE ELSE  FALSE END ) AS HAVECHILD   FROM "+BizLayer.TABLE_NAME+"  T  ORDER BY T.SORT ASC");
//		RenderLayuiBean renderBean = new RenderLayuiBean();
//		renderBean.setCode(0);
//		renderBean.setMsg("查询成功");
//		renderBean.setData(list);
//		renderBean.setCount(list.size());
//		this.renderJson(renderBean);
//	}
	
	public void listData() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("limit", 10);
		String name = getPara("name");
		String type = getPara("type");
		String isPublic = getPara("isPublic");
		String userId="";
		SimpleUser simpleUser = ShiroKit.getLoginUser();
		if (simpleUser != null) {
			userId=simpleUser.getId();
		}
		
		String sqlExceptSelect = " from " + BizLayer.TABLE_NAME + " o  where 1=1 ";
		
		if(StrKit.equals("1",isPublic)) {
			sqlExceptSelect += " and o.createUserId = '" + userId + "'   ";	
		}
		
		else if(StrKit.equals("0",isPublic)) {
			sqlExceptSelect += " and o.isPublic = '0'   ";	
		}else {
			if(!StrKit.equals(simpleUser.getUsername(),"system")) {
				sqlExceptSelect += " and ( o.createUserId = '" + userId + "' or  o.isPublic = '0' ) ";
			}
		}
		
		if (!StrKit.isBlank(name)) {
			sqlExceptSelect += " and o.name like '%" + name + "%'  ";
		}
		if (!StrKit.isBlank(type)) {
			sqlExceptSelect += " and o.type = '" + type + "'  ";
		}
		
		sqlExceptSelect += " order by o.sort asc  ";
		Page<BizLayer> page = BizLayer.dao.paginate(pageNumber, pageSize, "select * ", sqlExceptSelect);
		renderLayuiPage(0, page.getList(), "", page.getTotalRow());
	}
	
	/**
	 * 异步获取场景图层（有效）
	 */
	public void getAsyncTreeData() {
		renderJson(srv.getAsyncTreeData(this));
	}



	public void getTree() {
		boolean open = true;// 是否展开所有
		boolean ifOnlyLeaf = false;// 是否只选叶子
		if (StrKit.notBlank(getPara("ifOnlyLeaf"))) {// 是否查询所有孩子
			if ("1".equals(getPara("ifOnlyLeaf"))) {
				ifOnlyLeaf = true;
			}
		}
		String type = getPara("type");
		String sceneId = getPara("sceneId");
		List<BizLayer> modelList = BizLayer.dao.getChildrenAllTree("root", type,sceneId);
		List<ZtreeNode> nodelist = BizLayer.dao.toZTreeNode(modelList, open, ifOnlyLeaf);// 数据库中的菜单
		renderJson(nodelist);
	}

	public void save() {
		BizLayer model = getModel(BizLayer.class);
		if (StrKit.notBlank(model.getId())) {
			if(StrKit.isBlank(model.getCode())) {
				model.setCode(PinYinUtil.getPinyin(model.getName()));
			}
			if (model.update()) {
				renderSuccess("更新成功！", model);
			} else {
				renderError("更新失败！");
			}
		} else {
			model.setId(UuidUtil.getUUID());
			if(StrKit.isBlank(model.getCode())) {
				model.setCode(PinYinUtil.getPinyin(model.getName()));
			}
			if (StrKit.isBlank(model.getParentId()))
				model.setParentId("root");
			if (model.save()) {
				renderSuccess("保存成功！", model);
			} else {
				renderError("保存失败！");
			}
		}
	}

	public void delete() throws Exception {
		String id = getPara("id");
		Page<BizLayer> page = BizLayer.dao.paginate(1, 1, "SELECT * "," FROM " + BizLayer.TABLE_NAME + " WHERE PARENTID=? ", id);
		if (page.getTotalRow() == 0) {
			BizLayer bizLayer = BizLayer.dao.findById(id);
			if (bizLayer != null) {
				if (bizLayer.delete()) {
					renderSuccess("删除成功", bizLayer);
					Db.delete("delete from "+Point.TABLE_NAME+" where layerId=? ",bizLayer.getId());
				} else {
					renderError("删除失败！");
				}
			} else {
				renderError("无效操作，数据不存在!");
			}

		} else {
			renderError("当前节点有子节点,不允许删除!");
			return;
		}
	}
	
	@SuppressWarnings("resource")
	public void execlImport() throws IOException {
		UploadFile uploadFile = getFile();
		if(uploadFile==null) {
			renderError("导入失败，文件为空参数不完整！");
			return;
		}
		
		String type = getPara("type");
		if(StrKit.isBlank(type)) {
			renderError("导入失败，请选择图层类型！");
			return;
		}
		SimpleUser simpleUser = ShiroKit.getLoginUser();
		
		Workbook workbook = null;
		File excelFile = new File(uploadFile.getFile().getPath());
		InputStream is = new FileInputStream(excelFile);
		if (excelFile.getName().endsWith("xlsx")) {
			workbook = new XSSFWorkbook(is);
		} else {
			workbook = new HSSFWorkbook(is);
		}
		int unmber=0;
		List<String> layerName= new LinkedList<String>();
		for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
			Sheet sheet = workbook.getSheetAt(numSheet);
			if (sheet == null) {
				continue;
			}
			for (int i=1;i<sheet.getLastRowNum()+1;i++) {
				Row row = sheet.getRow(i);
				BizLayer bizLayerOld = BizLayer.dao.findFirst("select * from "+BizLayer.TABLE_NAME+" where name=?",row.getCell(1).getStringCellValue());
				if(bizLayerOld!=null) {
					layerName.add(row.getCell(1).getStringCellValue());
					continue;
				}
				
				BizLayer bizLayer = new BizLayer();
				bizLayer.setId(UuidUtil.getUUID());
				bizLayer.setName(row.getCell(1).getStringCellValue());
				bizLayer.setCode(row.getCell(2).getStringCellValue());
				bizLayer.setSort(Integer.parseInt(row.getCell(0).getStringCellValue()));//simpleUser
				bizLayer.setCreateUserId(simpleUser.getId());
				bizLayer.setCreateUserName(simpleUser.getName());
				bizLayer.setParentId("root");
				bizLayer.setIsPublic("0");
				bizLayer.setType(type);
				bizLayer.setShow("1");
				if(bizLayer.save()) {
					unmber++;
				}
			}
			
		}
		renderSuccess("导入成功【"+unmber+"】条数据，"+JsonKit.toJson(layerName)+"图层已存在！");
	}
	
	public void downLoadTpl() {
		
	}
	
//	public void common() {
//		this.set("sceneId", this.get("sceneId"));
//		render("common.html");
//	}

//	public void getLayerById() throws Exception {
//		String id = getPara("id");
//		BizLayer bizLayer = BizLayer.dao.findById(id);
//		if (bizLayer != null) {
//			if(StrKit.equals("Points", bizLayer.getType())) {
//				BizStylePoint defaultStyle = BizStylePoint.dao.findById(bizLayer.getDefaultStyleId());
//				BizStylePoint hoverStyle = BizStylePoint.dao.findById(bizLayer.getHoverStyleId());
//				BizStylePoint selectedStyle = BizStylePoint.dao.findById(bizLayer.getSelectedStyleId());
//				bizLayer.setDefaultStyleName(defaultStyle==null?"":defaultStyle.getName());
//				bizLayer.setHoverStyleName(hoverStyle==null?"":hoverStyle.getName());
//				bizLayer.setSelectedStyleName(selectedStyle==null?"":selectedStyle.getName());
//			}else if(StrKit.equals("Polylines", bizLayer.getType())) {
//				BizStyleLine defaultStyle = BizStyleLine.dao.findById(bizLayer.getDefaultStyleId());
//				BizStyleLine hoverStyle = BizStyleLine.dao.findById(bizLayer.getHoverStyleId());
//				BizStyleLine selectedStyle = BizStyleLine.dao.findById(bizLayer.getSelectedStyleId());
//				bizLayer.setDefaultStyleName(defaultStyle==null?"":defaultStyle.getName());
//				bizLayer.setHoverStyleName(hoverStyle==null?"":hoverStyle.getName());
//				bizLayer.setSelectedStyleName(selectedStyle==null?"":selectedStyle.getName());
//			}else if(StrKit.equals("Polygons", bizLayer.getType())) {
//				BizStylePolygon defaultStyle = BizStylePolygon.dao.findById(bizLayer.getDefaultStyleId());
//				BizStylePolygon hoverStyle = BizStylePolygon.dao.findById(bizLayer.getHoverStyleId());
//				BizStylePolygon selectedStyle = BizStylePolygon.dao.findById(bizLayer.getSelectedStyleId());
//				bizLayer.setDefaultStyleName(defaultStyle==null?"":defaultStyle.getName());
//				bizLayer.setHoverStyleName(hoverStyle==null?"":hoverStyle.getName());
//				bizLayer.setSelectedStyleName(selectedStyle==null?"":selectedStyle.getName());
//			}
//			renderSuccess("成功！", bizLayer);
//		} else {
//			renderError("数据已经不存在！");
//		}
//	}
//	
//	public void getLayerByCode() throws Exception {
//		String code = getPara("code");
//		String sql = "select * from "+BizLayer.TABLE_NAME+" where 1=1 ";
//		if(!StrKit.isBlank(code)) { 
//			sql += " and code like '%"+code+"%' ";
//		}
//		List<BizLayer> bizLayers = BizLayer.dao.find(sql);
//		if(bizLayers!=null && bizLayers.size()>0) {
//			renderSuccess("查询成功！", bizLayers);
//		}else {
//			renderError("未查到数据！");
//		}
//	}
//	
//	public void getLayerAll() throws Exception {
//		String sql = "select * from "+BizLayer.TABLE_NAME+" where 1=1 and type <> 'folder' ";
//		List<BizLayer> bizLayers = BizLayer.dao.find(sql);
//		if(bizLayers!=null && bizLayers.size()>0) {
//			renderSuccess("查询成功！", bizLayers);
//		}else {
//			renderError("未查到数据！");
//		}
//	}
//	
//	public void getLayerByParentId() throws Exception {
//		String parentId = getPara("parentId");
//		List<BizLayer> bizLayers = BizLayer.dao.find("select * from "+BizLayer.TABLE_NAME+" where parentId=?",parentId);
//		if (bizLayers!=null && bizLayers.size()>0) {
//			renderSuccess("成功！", bizLayers);
//		} else {
//			renderError("数据已经不存在！");
//		}
//	}
//	
//	public void getLayerByUser() {
//		String sceneId = this.get("sceneId");
//		String code = this.get("code");
//		SimpleUser user = ShiroKit.getLoginUser();
//		if(user!=null && !StrKit.equals("system",user.getUsername())) {
//			String sql = " FROM biz_layer a where 1=1 and sceneId=? "
//					+ " and a.parentId in ( select layerId from "+SysUserSceneLayerPermissions.TABLE_NAME+" where userId='"+user.getId()+"' )  ";
//			if(!StrKit.isBlank(code)) {
//				sql+=" and code= '"+code+"' ";
//			}
//			sql+="order by a.sort asc";
//			List<BizLayer> olist = BizLayer.dao.find("SELECT a.*,(CASE WHEN (select count(id) from biz_layer where a.id=parentId ) >0 THEN true ELSE false END) AS isParent "+sql,sceneId);
//			List<ZtreeNode> nodelist = new ArrayList<ZtreeNode>();
//			for (BizLayer o : olist) {
//				ZtreeNode node = BizLayer.dao.toZTreeNode(o);
//				node.setIsParent(StrKit.equals("1", o.get("isParent") + "") ? true : false);
//				node.setParentId(o.getParentId());
//				node.setChecked(StrKit.equals("1", o.getShow() + "") ? true : false);
//				nodelist.add(node);
//			}
//			renderJson(nodelist);
//		}else {
//			this.renderError("");
//		}
//	}
//	
//	public void getCommunityFolderByUser() {
//		String sceneId = this.get("sceneId");
//		String code = this.get("code","community");
//		SimpleUser user = ShiroKit.getLoginUser();
//		if(user!=null && !StrKit.equals("system",user.getUsername())) {
//			String sql = " FROM biz_layer a where 1=1 and sceneId=? "
//					+ " and a.parentId in ( select layerId from "+SysUserSceneLayerPermissions.TABLE_NAME+" where userId='"+user.getId()+"' )  ";
//			if(!StrKit.isBlank(code)) {
//				sql+=" and code like '%"+code+"%' ";
//			}
//			sql+="order by a.sort asc";
//			List<BizLayer> olist = BizLayer.dao.find("SELECT a.*,(CASE WHEN (select count(id) from biz_layer where a.id=parentId ) >0 THEN true ELSE false END) AS isParent "+sql,sceneId);
//			List<ZtreeNode> nodelist = new ArrayList<ZtreeNode>();
//			for (BizLayer o : olist) {
//				ZtreeNode node = BizLayer.dao.toZTreeNode(o);
//				node.setIsParent(StrKit.equals("1", o.get("isParent") + "") ? true : false);
//				node.setParentId(o.getParentId());
//				node.setChecked(StrKit.equals("1", o.getShow() + "") ? true : false);
//				nodelist.add(node);
//			}
//			renderJson(nodelist);
//		}else {
//			this.renderError("");
//		}
//	}
//	
//	public void getMapFolderByUser() {
//		String sceneId = this.get("sceneId");
//		String code = this.get("code","map");
//		SimpleUser user = ShiroKit.getLoginUser();
//		if(user!=null && !StrKit.equals("system",user.getUsername())) {
//			String sql = " FROM biz_layer a where 1=1 and sceneId=? "
//					+ " and a.parentId in ( select layerId from "+SysUserSceneLayerPermissions.TABLE_NAME+" where userId='"+user.getId()+"' ) ";
//			if(!StrKit.isBlank(code)) {
//				sql+=" and a.parentId in (select id from "+BizLayer.TABLE_NAME+" where code like '%"+code+"%') ";
//			}
//			sql+="order by a.sort asc";
//			List<BizLayer> olist = BizLayer.dao.find("SELECT a.*,(CASE WHEN (select count(id) from biz_layer where a.id=parentId ) >0 THEN true ELSE false END) AS isParent "+sql,sceneId);
//			List<ZtreeNode> nodelist = new ArrayList<ZtreeNode>();
//			for (BizLayer o : olist) {
//				ZtreeNode node = BizLayer.dao.toZTreeNode(o);
//				node.setIsParent(StrKit.equals("1", o.get("isParent") + "") ? true : false);
//				node.setParentId(o.getParentId());
//				node.setChecked(StrKit.equals("1", o.getShow() + "") ? true : false);
//				nodelist.add(node);
//			}
//			renderJson(nodelist);
//		}else {
//			this.renderError("");
//		}
//	}
	private String rootPath = PathKit.getWebRootPath();
	ExecutorService executor = Executors.newFixedThreadPool(20);
	public void uploadKml() {
		UploadFile uploadFile = getFile();
		try {
			
			String id=this.getPara("id");
			if(StrKit.isBlank(id)) {
				this.renderError("请选择导入数据的图层！");
				return;
			}
			
			BizLayer layer=BizLayer.dao.findById(id);
			if(layer==null) {
				this.renderError("未查询到图层信息！");
				return;
			}
			
			String path = "/upload/layer/"+id+"/" + uploadFile.getFileName().replace(" ", "");
			File file = new File(rootPath+path);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			if (file.exists()) {
				file.delete();
			}
			
			if(uploadFile.getFile().renameTo(file)) {
				renderSuccess("上传成功，后台异步导入中，请稍后查看！");
			    CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {
			        @Override
			        public Integer get() {
			            try {
							KmlParser parser = new KmlParser();
							KmlProperty kmlProperty;
							File file = new File(rootPath+path);
							kmlProperty = parser.parseKmlForJAK(file);
							assert kmlProperty != null;
							if (kmlProperty.getKmlPoints().size() > 0) {
								for (int i=0;i<kmlProperty.getKmlPoints().size();i++) {
									srv.saveForBizPoint(layer.getId(), kmlProperty.getKmlPoints().get(i));
								}
							}
							if (kmlProperty.getKmlLines().size() > 0) {
								for (KmlLine k : kmlProperty.getKmlLines()) {
									srv.saveForBizLine(layer.getId(), k);
								}
							}
							if (kmlProperty.getKmlPolygons().size() > 0) {
								for (KmlPolygon k : kmlProperty.getKmlPolygons()) {
									srv.saveForKmlPolygon(layer.getId(), k);
								}
							}
							file.delete();
			            } catch (Exception e) {
			                e.printStackTrace();
			            }
			            return 3;
			        }
			    }, executor);
			    future.thenAccept(e -> System.out.println(e));
			}else {
				renderError("导入失败！");
			}
		} catch (Exception e) {
			renderError(e.getMessage());
		}
	}
}
